﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace XGame.Input
{
    class KeyboardControl : GameComponent
    {
        /// <summary>
        /// The function that the control will be bound too when the control is pressed
        /// </summary>
        public event EventHandler<EventArgs> ControlPressed;

        /// <summary>
        /// The Function that the control will be bound to when the control is released
        /// </summary>
        public event EventHandler<EventArgs> ControlReleased;

        private bool controlIsPressed;

        /// <summary>
        /// A property that tells if the control is pressed or not.
        /// </summary>

        public bool ControlIsPressed
        {
            get { return controlIsPressed; }
        }





        private KeyboardState currentKeyboardState;
        private KeyboardState previousKeyboardState;

        private Keys KeyBinding;

        /// <summary>
        /// An object representing a button on the keyboard that can be mapped to a function
        /// </summary>
        /// <param name="KeyBinding"> The key on the Keyboard that the control will be bound too.</param>
        public KeyboardControl(Keys KeyBinding, Game game):base(game)
        {
            
            this.KeyBinding = KeyBinding;
            controlIsPressed = false;
        }

        public override void Update(GameTime gameTime)
        {
            if (currentKeyboardState.IsKeyUp(KeyBinding) && previousKeyboardState.IsKeyDown(KeyBinding))
            {
                //throw released event
                if (ControlReleased != null)
                    ControlReleased(this, EventArgs.Empty);

                controlIsPressed = false;
                
            }
            if (currentKeyboardState.IsKeyDown(KeyBinding) && previousKeyboardState.IsKeyUp(KeyBinding))
            {
                //throw pressed event
                if (ControlPressed != null)
                    ControlPressed(this, EventArgs.Empty);
                
                controlIsPressed = true;
            }

            base.Update(gameTime);
        }
    }
}
